<template>
  <div class="hospital-management">

    <!-- 页面标题 -->
    <h2 class="page-title">医院管理</h2>

    <!-- 查询条件区 -->
    <div class="query-section">
      <el-form :inline="true" :model="queryParams" class="query-form">
        <el-form-item label="医院名称">
          <el-input v-model="queryParams.name" placeholder="请输入医院名称" clearable />
        </el-form-item>
        <el-form-item label="医院类型">
          <el-select v-model="queryParams.type" placeholder="全部" clearable>
            <el-option
                v-for="item in hospitalTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="医院等级">
          <el-select v-model="queryParams.level" placeholder="请选择" clearable>
            <el-option
                v-for="item in hospitalLevels"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区 -->
    <div class="action-section">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selection.length === 0">
        <el-icon><Delete /></el-icon>删除
      </el-button>
      <el-button @click="handleBatchEnable" :disabled="selection.length === 0">
        <el-icon><CircleCheck /></el-icon>上架
      </el-button>
      <el-button @click="handleBatchDisable" :disabled="selection.length === 0">
        <el-icon><CircleClose /></el-icon>下架
      </el-button>
      <span class="selection-count" v-if="selection.length > 0">
        已选择{{ selection.length }}项，可以进行批量操作
      </span>
    </div>

    <!-- 医院列表 -->
    <div class="hospital-list">
      <el-table
          :data="hospitalData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="医院名称" width="180" />
        <el-table-column prop="avatar" label="医院头像" width="120">
          <template #default="{ row }">
            <el-avatar :size="50" :src="row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="医院地址" />
        <el-table-column prop="type" label="医院类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.type === '公立医院' ? 'primary' : 'success'">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="医院等级" width="120">
          <template #default="{ row }">
            <el-tag effect="dark" :type="getLevelTagType(row.level)">
              {{ row.level }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="是否上架" width="120">

          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '已上架' : '已下架' }}
            </el-tag>
            <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              医院详情
            </el-button>
            <el-button type="success" size="small" @click="handleSetAppointment(row)">
              设置体检预约
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页插件 ========================================== =============================== -->
    <div class="demo-pagination-block">
      <!--
                  1. current-page  ： 当前页   （重要）
                  2. page-size  : 每页显示条数（重要）
                  3. page-sizes ： 分页类型
                  4. small： 字体大小
                  5. disabled： 是否可用
                  6. background： 按钮颜色
                  7. total： 总数据条数（重要）

          -->
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[2, 3, 4, 5]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 分页插件 ========================================== =============================== -->

  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import axios from "axios";
import {router} from "@/router/index.js";



// 分页模型定义=======================================================================
let pageNum = ref(1);
let pageSize = ref(3);
let total = ref(1);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const handleSizeChange = (val) => {
  pageSize.value = val;
  getHospitalList();
}
const handleCurrentChange = (val) => {
  // 将这个val数字赋值给 pageNum
  pageNum.value = val;
  getHospitalList();
}
// 分页模型定义=======================================================================



// 医院类型选项
const hospitalTypes = ref([])
const gethospitalTypes = () => {
  axios.get("/hospital/getHospitalType").then(res => {
    // 确保数据结构有value和label
    hospitalTypes.value = res.data.obj.map(item => ({
      value: item,
      label: item
    }))
  })
}
// 医院等级选项
const hospitalLevels =ref([])
const gethospitalLevels=()=>{
  axios.get("/hospital/getHospitalLevel").then(res => {
    hospitalLevels.value = res.data.obj.map(item => ({
      value: item,
      label: item
    }))
  })
}
// 医院数据
const hospitalData = ref([])
const getHospitalList=()=>{
  axios.get(`/hospital/getHospital/${pageNum.value}/${pageSize.value}`).then(res=>{
    hospitalData.value = res.data.data
    total.value = res.data.total;
    ElMessage.success('查询成功');
  })
}

// 查询处理
// 查询参数
const queryParams = reactive({
  name: '',
  type: '',
  level: ''
})
const handleQuery = () => {
  // 构造符合Hospital对象的查询参数
  const searchParams = {
    name: queryParams.name,
    type: queryParams.type,
    level: queryParams.level
  }

  axios.post(`/hospital/searchHospital/${pageNum.value}/${pageSize.value}`, searchParams, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(res => {
    hospitalData.value = res.data.data
    total.value = res.data.total
    ElMessage.success('查询成功')
  }).catch(error => {
    ElMessage.error('查询失败: ' + error.message)
  })
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.type = ''
  queryParams.level = ''
  handleQuery()
}

// 添加医院
const handleAdd = () => {
  router.push('addHospital')
  ElMessage.info('添加医院')
}

// 批量删除
const selection = ref([])
const handleBatchDelete = () => {
  if (selection.value.length === 0) return

  ElMessageBox.confirm('确定要删除选中的医院吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 1. 提取ID数组
    const ids = selection.value.map(item => item.id)

    // 2. 发送请求
    axios.post('/hospital/batchDeleteHospital', ids, {
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getHospitalList() // 刷新列表
        selection.value = [] // 清空选中项
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }).catch(error => {
      ElMessage.error('删除失败: ' + error.message)
    })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量上架
const handleBatchEnable = () => {
  if (selection.value.length === 0) return;
  ElMessageBox.confirm('确定要上架选中的医院吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selection.value.map(item => item.id);
      const response = await axios.post('/hospital/batchUpdateStatus', {
        ids: ids,
        status: 1 // 上架状态
      });

      if (response.data.code === 200) {
        ElMessage.success(`已成功上架${selection.value.length}家医院`);
        getHospitalList(); // 刷新列表
        selection.value = []; // 清空选中项
      } else {
        ElMessage.error( '批量上架失败');
      }
    } catch (error) {
      ElMessage.error('批量上架失败: ');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

// 批量下架
const handleBatchDisable = () => {
  if (selection.value.length === 0) return;

  ElMessageBox.confirm('确定要下架选中的医院吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selection.value.map(item => item.id);
      const response = await axios.post('/hospital/batchUpdateStatus', {
        ids: ids,
        status: 0 // 下架状态
      });

      if (response.data.code === 200) {
        ElMessage.success(`已成功下架${selection.value.length}家医院`);
        getHospitalList(); // 刷新列表
        selection.value = []; // 清空选中项
      } else {
        ElMessage.error( '批量下架失败');
      }
    } catch (error) {
      ElMessage.error('批量下架失败: ');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
}

// 表格选择变化
const handleSelectionChange = (val) => {
  selection.value = val
}

// 查看医院详情
const handleViewDetail = (row) => {
  router.push({
    name: 'hospitalDetail',  // 使用命名路由
    params: { id: row.id }  // 明确传递params
  })
}
// 设置体检预约
const handleSetAppointment = (row) => {
  ElMessage.info(`设置医院: ${row.name} 的体检预约`)
}

// 状态变更 - 单个医院
const handleStatusChange = async (row) => {
  try {
    const response = await axios.post('/hospital/updateStatus', {
      id: row.id,
      status: row.status
    });
    if (response.data.code === 200) {
      const action = row.status === 1 ? '上架' : '下架';
      ElMessage.success(`已${action}医院: ${row.name}`);
      getHospitalList(); // 刷新列表
    } else {
      // 失败时恢复原状态
      row.status = row.status === 1 ? 0 : 1;
      ElMessage.error( '状态更新失败');
    }
  } catch (error) {
    // 失败时恢复原状态
    row.status = row.status === 1 ? 0 : 1;
    ElMessage.error('状态更新失败: ');
  }
}





//获取等级标签类型
const getLevelTagType = (level) => {
  if (level.includes('三级甲等')) return 'danger'
  if (level.includes('三级乙等')) return 'warning'
  if (level.includes('二级甲等')) return 'success'
  if (level.includes('二级乙等')) return 'info'
 return 'primary';
}

onMounted(() => {
  getHospitalList();
  gethospitalTypes();
  gethospitalLevels();
})
</script>

<style scoped>
.hospital-management {
  padding: 20px;
  background-color: #fff;
}

.page-title {
  margin: 20px 0;
  font-size: 20px;
  color: #333;
}

.query-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.action-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.selection-count {
  margin-left: 15px;
  font-size: 14px;
  color: #666;
}

.hospital-list {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}

.el-tag {
  margin: 2px;
}
</style>